<template>
  <div class="water-quality-container">
    <div class="popup-header">
      <h3>{{ featureData.name || '地图要素' }}</h3>
      <span class="close-btn" @click="closePopup">×</span>
    </div>
    <el-tabs v-model="activeName">
               <el-tab-pane label="基础信息" name="first"> 
         <div class="pollution-info">
            <div class="info-item">
              <label>站点名称:</label>
              <span>{{ stationInfo.segmentname || '--' }}</span>
            </div>
                <div class="info-item">
              <label>河流名称:</label>
              <span>{{ stationInfo.rivername || '--' }}</span>
            </div>
            <div class="info-item">
              <label>行政区划:</label>
              <span>{{ stationInfo.county || '--' }}</span>
            </div>
            <div class="info-item">
              <label>断面类型:</label>
            <span>{{ stationInfo.controllevel || '--' }}</span>
            </div>
            <div class="info-item">
              <label>经度:</label>
              <span>{{ stationInfo.longitude || '--' }}</span>
            </div>
            <div class="info-item">
              <label>纬度:</label>
              <span>{{ stationInfo.latitude || '--' }}</span>
            </div>
            <div class="info-item">
              <label>目标水质:</label>
              <span>{{ stationInfo.targetlevelname || '--' }}</span>
            </div>
                 <div class="info-item">
              <label>地址:</label>
              <span>{{ stationInfo.segmaddress || '--' }}</span>
            </div>
        
          </div>
      </el-tab-pane>
      <el-tab-pane label="数据" name="second">
        <!-- 图表控制区域 -->
        <div class="chart-controls">

          <div class="time-range-control">
            <el-date-picker v-model="dateRange" :type="datePickerType" range-separator="至"
              :start-placeholder="datePickerStartPlaceholder" :end-placeholder="datePickerEndPlaceholder"
              @change="handleDateChange" size="small">
            </el-date-picker>
            <el-button type="primary" @click="handleQuery" class="query-btn" size="small">
              <i class="fa fa-search"></i> 查询
            </el-button>
          </div>
        </div>

        <!-- 水质状况区域 -->
        <el-card class="water-quality-card" shadow="never">


          <!-- 新增的select选择框 -->
          <div class="select-container">
            <el-select v-model="selectedOption" placeholder="请选择" size="small" @change="handleSelectChange">
              <el-option v-for="item in selectOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>

          <!-- 图表容器 -->

          <!-- 图表容器 -->
          <div class="chart-container">
            <el-card shadow="never">
              <div ref="chartRef" class="echart-container"></div>
            </el-card>
          </div>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="视频" name="third">
        <video class="black-video-placeholder" controls="false"></video>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { drinkwateritemlistbytime, bussinessItemData } from '@/views/biz/api/shuiyuandi'
import { getinfo} from '@/views/biz/api/water'


export default {
  name: 'WaterQualityPopup',
  data() {
    return {
             activeName: 'first',
      controlLevel: '县控',
      stationInfo: {},
      autoStationInfo: {},
      exceedAlertTitle: '',
      // 时间周期：hour, day, month
      timePeriod: 'day',
      // 日期范围
      dateRange: [
      ],
      // 水质指标数据
      indicators: [],
      targetQuality: 2,
      times: [],
      qualityData: [],
      monitoringData: {},
      // 图表实例
      chart: null,
      levelMap: {
        "劣Ⅴ类": 6,
        "Ⅴ类": 5,
        "Ⅳ类": 4,
        "Ⅲ类": 3,
        "Ⅱ类": 2,
        "Ⅰ类": 1,
        "无类别": 0
      },
      // 新增的select相关数据
      selectedOption: '',
      selectOptions: [
      ]

    }
  },
  props: {
    featureId: {
      type: String,
      default: ''
    },
    featureData: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    datePickerType() {
      switch (this.timePeriod) {
        case 'hour':
          return 'datetimerange';
        case 'day':
          return 'daterange';
        case 'month':
          return 'monthrange';
        default:
          return 'datetimerange';
      }
    },
    datePickerStartPlaceholder() {
      switch (this.timePeriod) {
        case 'hour':
          return '开始时间';
        case 'day':
          return '开始日期';
        case 'month':
          return '开始月份';
        default:
          return '开始时间';
      }
    },
    datePickerEndPlaceholder() {
      switch (this.timePeriod) {
        case 'hour':
          return '结束时间';
        case 'day':
          return '结束日期';
        case 'month':
          return '结束月份';
        default:
          return '结束时间';
      }
    },
    targetQualityText() {
      const qualityMap = {
        6: "劣Ⅴ类",
        5: "Ⅴ类",
        4: "Ⅳ类",
        3: "Ⅲ类",
        2: "Ⅱ类",
        1: "Ⅰ类"
      };
      return qualityMap[this.targetQuality] || '未知';
    }
  },
  watch: {
    featureId: {
      handler(newVal, oldVal) {
        if (newVal) {
          //console.log('featureId', newVal)
        }
      },
      immediate: true
    },
  },
  mounted() {

    this.initDateRange();
    this.getbaseinfo()
    this.getBussinessItemData()


    // 监听窗口大小变化，调整图表尺寸
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    // 销毁图表实例，释放资源
    if (this.chart) {
      this.chart.dispose()
    }
    // 移除事件监听
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    closePopup() {
      this.$emit('close');
    },
    formatHour(date) {
      if (!date) return '';
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    formatDate(date) {
      if (!date) return '';
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    formatMonth(date) {
      if (!date) return '';
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      return `${year}-${month}`;
    },
    /**
   * 初始化日期范围
   * 根据timePeriod的值设置起始和结束时间
   * hour: 前24小时
   * day: 前7天
   * month: 前12个月
   */
    initDateRange() {
      const end = new Date();
      const start = new Date();
      start.setMinutes(0, 0, 0);

      switch (this.timePeriod) {
        case 'hour':
          end.setMinutes(0, 0, 0); // 将分钟、秒、毫秒设置为0，实现小时取整
          start.setTime(start.getTime() - 3600 * 1000 * 24); // 前24小时
          break;
        case 'day':
          end.setHours(0, 0, 0, 0); // 设置为当天0点
          start.setHours(0, 0, 0, 0);
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 6); // 前7天
          break;
        case 'month':
          end.setDate(1); // 设置为当月1号
          end.setHours(0, 0, 0, 0);
          start.setMonth(start.getMonth() - 12); // 前12个月
          break;
      }

      this.dateRange = [start, end];
    },

    getbaseinfo() {
      getinfo({ id: this.featureId }).then(res => {
        this.stationInfo = res.data;
        // 优化targetLevelName为NULL时的处理
        if (res.data.targetlevelname && this.levelMap[res.data.targetlevelname] !== undefined) {
          this.baseinfo=res.data;
          this.targetQuality = this.levelMap[res.data.targetlevelname];
        } else {

          this.targetQuality = 2; // 默认为Ⅱ类
        }
      })
    },

    /**
    * 获取业务项数据
    * 该函数用于获取饮品自动售货相关的业务项数据，并将其转换为下拉选项格式
    * 数据获取成功后会自动选择第一个选项作为默认值
    */
    getBussinessItemData() {
      // 添加加载状态
      this.loading = true;
      bussinessItemData({ bussinessCategoryCode: "DrinkAuto" }).then(res => {
        // 数据验证，确保 res.data 存在且为数组
        if (res && Array.isArray(res.data)) {
          // 修正数据结构：使用 { value, label } 对象数组
          this.selectOptions = res.data.map(item => ({
            value: item.itemCode,
            label: item.itemName
          }));
          this.selectedOption = this.selectOptions[0].value;
          this.getMonitoringData();
        } else {
          this.selectOptions = [];
          console.warn('Business item data is not in expected format:', res);
        }
      }).catch(error => {
        // 错误处理
        this.selectOptions = [];
        console.error('Failed to fetch business item data:', error);
      }).finally(() => {
        // 重置加载状态
        this.loading = false;
      })
    },
    getOption() {
      // ECharts配置项
      const option = {
        title: {
          text: '水质趋势图',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          },
          padding: [0, 0, 20, 0]
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#ddd',
          borderWidth: 1,
          textStyle: {
            color: '#333'
          },
          formatter: params => {
            let result = `<div style="font-weight:bold">时间: ${params[0].name}</div>`
            params.forEach(item => {
              if (item.seriesType === 'line') {
                result += `<div style="display:flex;align-items:center;margin-top:5px">
                  <span style="display:inline-block;width:10px;height:10px;background-color:${item.color};margin-right:5px;border-radius:50%"></span>
                  ${item.seriesName}: ${item.value}
                </div>`
              }
            })
            return result
          }
        },
        legend: {
          show: true,
          top: 'bottom',
          left: 'center'
        },
        grid: {
          left: '3%',
          right: '7%',
          bottom: '20%',
          top: '15%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {
              title: '保存图片'
            },
            dataZoom: {
              title: {
                zoom: '区域缩放',
                back: '缩放还原'
              }
            },
            restore: {
              title: '还原'
            }
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.times,
          // axisLabel: {
          //   interval: 'auto',
          //   maxInterval: 10
          // },
          name: '监测时间',
          nameLocation: 'middle',
          nameGap: 30
        },
        yAxis: [
          {
            type: 'value',
            name: '水质',
            nameLocation: 'middle',
            nameGap: 50,
            splitLine: {
              lineStyle: {
                color: 'rgba(0, 0, 0, 0.05)'
              }
            }
          }
        ],
        series: [
          {
            name: '水质',
            type: 'line',
            data: this.qualityData,
            symbol: 'circle',
            symbolSize: 6,
            emphasis: {
              symbolSize: 8
            },
            lineStyle: {
              width: 3,
              color: '#4bc0c0'
            },
            itemStyle: {
              color: '#4bc0c0'
            },
            smooth: true,
            // markLine: {
            //   data: [
            //     {
            //       type: 'value',
            //       name: '目标水质',
            //       yAxis: this.targetQuality,
            //       lineStyle: {
            //         color: '#dc3545',
            //         type: 'dashed',
            //         width: 2
            //       },
            //       label: {
            //         show: true,
            //         position: 'end',
            //         color: '#dc3545'
            //       }
            //     },

            //   ]
            // }
          }
        ],
        dataZoom: [
          {
            type: 'inside',
            xAxisIndex: 0,
            start: 0,
            end: 100
          },
          {
            show: !this.isMobile, // 移动端隐藏滑动条
            type: 'slider',
            xAxisIndex: 0,
            start: 0,
            end: 100,
            bottom: 50
          }
        ],
        animation: true,
        animationDuration: 1000,
        animationEasing: 'cubicOut'
      }
      this.chart.setOption(option, true)

    },
    // 渲染图表
    renderChart() {
      if (!this.chart) {
        this.chart = echarts.init(this.$refs.chartRef)
        this.getOption()
      }
      else {
        this.getOption()
      }
    },

    // 转换函数：生成value数组
    // 转换函数：生成value数组
    convertData(data) {
      // 从数据列表中提取时间数组和数值数组
      const dateList = data.map(item => item.sampleDate);
      const valueList = data.map(item => parseFloat(item.effectiveValue));

      // 返回包含dateList和value的新对象
      return {
        dateList,
        value: valueList
      };
    },
    getMonitoringData() {
      let apiFunction;
      let startTime;
      let endTime;
      startTime = this.formatDate(this.dateRange[0]);
      endTime = this.formatDate(this.dateRange[1]);


      apiFunction = drinkwateritemlistbytime;

      apiFunction({
        segmentId: this.featureId,
        beginDate: startTime,
        endDate: endTime,
        itemCode: this.selectedOption
      }).then(res => {
        this.monitoringData = this.convertData(res.data.list);
        this.times = this.monitoringData.dateList;
        this.qualityData = this.monitoringData.value;
        this.renderChart();
      }).catch(error => {
        console.error('获取监测数据失败:', error);
      });
    },


    // 处理日期范围变化
    handleDateChange() {
      if (!this.dateRange || this.dateRange.length !== 2) {
        this.$message.error('请选择开始时间和结束时间')
        return
      }

      if (this.dateRange[0] > this.dateRange[1]) {
        this.$message.error('开始时间不能晚于结束时间')
        return
      }
      this.getMonitoringData();
    },

    // 处理查询
    handleQuery() {
      if (!this.dateRange || this.dateRange.length !== 2) {
        this.$message.error('请选择开始时间和结束时间')
        return
      }

      if (this.dateRange[0] > this.dateRange[1]) {
        this.$message.error('开始时间不能晚于结束时间')
        return
      }
      this.getMonitoringData();


    },


    handleSelectChange() {
      if (!this.dateRange || this.dateRange.length !== 2) {
        this.$message.error('请选择开始时间和结束时间')
        return
      }

      if (this.dateRange[0] > this.dateRange[1]) {
        this.$message.error('开始时间不能晚于结束时间')
        return
      }
      this.getMonitoringData();
    },
    // 处理窗口大小变化
    handleResize() {
      if (this.chart) {
        this.chart.resize()
      }
    }
  }
}
</script>

<style scoped>
.water-quality-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 15px;
  background-color: #f9fafb;
}

.popup-header {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.popup-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: calc(100% - 30px);
}

.close-btn {
  cursor: pointer;
  font-size: 20px;
  color: #909399;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #409eff;
}


.tags-row {
  margin-bottom: 15px;
}
.info-item {
  display: flex;
  margin-bottom: 10px;
  font-size: 14px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item label {
  width: 120px;
  color: #606266;
  font-weight: 500;
}

.info-item span {
  flex: 1;
  color: #303133;
}
.water-quality-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  /* 左右两端对齐 */
  align-items: center;
  /* 垂直居中对齐（可选） */
  width: 100%;
  /* 确保容器占满可用宽度 */
}

/* 字体加粗 */
.card-header div {
  font-weight: bold;
}

.evaluation-descriptions {
  margin-bottom: 20px;
  background-color: #f8fafc;
  padding: 10px;
}

.deep-color {
  color: #333 !important;
  font-weight: 500;
}

/* 加深 label 文字 */
.evaluation-descriptions ::v-deep .el-descriptions__label {
  color: #333 !important;
}

.indicators-title {
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.indicators-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.indicator-item {
  border-radius: 6px;
  padding: 5px;
  background-color: #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  border: 1px solid #eee;
}

.indicator-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.indicator-item.exceed-limit {
  border-left: 4px solid #f56c6c;
}

.indicator-item.normal {
  border-left: 4px solid #409eff;
}

.indicator-item.good {
  border-left: 4px solid #67c23a;
}

.indicator-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.indicator-name {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.indicator-status {
  font-size: 16px;
}

.indicator-item.exceed-limit .indicator-status {
  color: #f56c6c;
}

.indicator-item.normal .indicator-status {
  color: #409eff;
}

.indicator-item.good .indicator-status {
  color: #67c23a;
}

.indicator-main {
  margin-bottom: 8px;
}

.indicator-value {
  font-weight: bold;
  font-size: 18px;
  color: #333;
  margin-right: 5px;
}

.indicator-range {
  font-size: 12px;
  color: #999;
}

.indicator-footer {
  font-size: 12px;
}

.indicator-desc {
  color: #666;
}

.exceed-alert {
  margin-bottom: 20px;
  border-radius: 4px;
}

.chart-controls {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.period-control {
  width: 100%;
}

.time-range-control {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
  width: 100%;
}

.query-btn {
  white-space: nowrap;
}

.echart-container {
  width: 600px;
  height: 300px;
}
.black-video-placeholder {
  background-color: #000;
  width: 500px;
  height: 300px;
  border-radius: 4px;
  object-fit: cover;
}
/* 响应式调整 */
/* @media (max-width: 768px) {
  .water-quality-container {
    padding: 10px;
  }

  .chart-controls {
    flex-direction: column;
    align-items: stretch;
  }

  .time-range-control {
    width: 100%;
  }

  .echart-container {
    height: 300px;
  }



  .indicators-container {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  }

  .indicator-item {
    padding: 12px;
  }

  .indicator-value {
    font-size: 16px;
  }
} */
</style>